<template>
<!--  平台管理页面-->
  <div class="page">
    <!-- 条件筛选 -->
    <div class="page_filter">
      <el-input v-model="form.unitTypeName" clearable placeholder="请输入单位名称"></el-input>
      <el-select v-model="form.unitType" clearable placeholder="请选择平台类型">
        <el-option
          v-for="item in EnumUnitTypeList"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
      <el-button class="common_btn-defalut" icon="el-icon-search" @click="form.page=1;queryList()">搜索</el-button>
    </div>

    <div class="page_main">
      <el-button icon="el-icon-plus" @click.stop="handleAdd" class="common_btn-small" v-if="isSuper">新增平台</el-button>
      <!-- table -->
      <div class="common_btnBox" >
        <i class="iconfont iconzongshu icon-size"></i>
        总数：{{form.total}}
      </div>
      <el-table
        :data="tableList"
        border>
        <el-table-column
          label="序号"
          fixed
          width="80">
          <template slot-scope="scope">
            {{getIndex(scope.$index)}}
          </template>
        </el-table-column>
        <el-table-column
          prop="unitTypeName"
          min-width="120"
          label="单位类型">
        </el-table-column>
        <el-table-column
          prop="platformName"
          min-width="160"
          label="单位名称">
        </el-table-column>
        <el-table-column
          prop="phone"
          width="140"
          label="联系电话">
        </el-table-column>
        <el-table-column
          prop="loginName"
          min-width="160"
          label="登录名">
        </el-table-column>
        <el-table-column
          prop="createTime"
          width="180"
          label="创建时间">
          <template slot-scope="scope">{{scope.row.createTime | formatTimer}}</template>
        </el-table-column>
        <el-table-column
          prop="updateTime"
          width="180"
          label="更新时间">
          <template slot-scope="scope">{{scope.row.updateTime | formatTimer}}</template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          width="220">
          <template slot-scope="scope">
            <button class="btn_edit" @click="handleEdit(scope.row)">编辑</button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="form.page"
        :page-size="form.pageSize"
           :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
              layout="sizes, prev, pager, next"
        :total="form.total">
      </el-pagination>
    </div>

    <!-- 新增编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="isShowDialog"
      :close-on-click-modal="false"
      width="520px">
      <!-- 具体form表单 -->
      <el-form label-position="right" ref="form" :rules="rules" :model="currentRow" label-width="80px">
        <el-form-item label="平台类型" prop="unitType">
          <!-- 平台类型 -->
          <el-select v-model="currentRow.unitType" :disabled="currentRow.id" clearable placeholder="选择平台类型">
            <el-option
              v-for="item in EnumUnitTypeList"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="单位名称" prop="platformName">
          <el-input v-model="currentRow.platformName" placeholder="输入单位名称" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="行政区" prop="region">
          <region-unit2 v-model="currentRow.region" :key="currentRow.region" placeholder="单位行政区"></region-unit2>
        </el-form-item>
        <el-form-item label="登录名" prop="loginName">
          <el-input v-model="currentRow.loginName" :disabled="isEditStatus" placeholder="输入登录名"></el-input>
        </el-form-item>
        <el-form-item label="密码" :prop="!isEditStatus ? null : 'password'">
          <el-input v-model.trim="currentRow.password" placeholder="输入密码" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="repeat" :required="!isEditStatus">
          <el-input v-model.trim="currentRow.repeat" placeholder="输入密码" type="password"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="currentRow.phone" placeholder="输入联系电话"></el-input>
        </el-form-item>

      </el-form>
      <!-- 操作按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="isShowDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validateForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {reviewQueryList, platformAdd, platformUpdate,} from '@/services/model/authority-mgmt'
import {filterEmpty} from '@/services/request'
import Format from '@/utils/format'
import {CHECK_EMAIL, CHECK_PASSWORD, CHECK_PHONE, CHECK_REPEAT, CHECK_USERNAME} from './validator'
import {querySubRegionList} from '@/services/model/address'
import RegionUnit2 from '@/components/region-unit2'
import cryptoJs from "crypto-js";
import Enums from '@/utils/enums'

export default {
  data() {
    return {
      propsCascader: {
        lazy: true,
        label: 'name',
        value: 'id',
        lazyLoad(node, resolve) {
          const {level, data} = node
          if (level === 0) {
            querySubRegionList().then(res => {
              const {data} = res
              resolve(data)
            })
          } else if (level === 1) {
            querySubRegionList({parentId: data.id}).then(res => {
              const {data} = res
              resolve(data)
            })
          } else if (level === 2) {
            querySubRegionList({parentId: data.id}).then(res => {
              const data = res.data.map(x => ({...x}))
              resolve(data)
            })
          } else if (level === 3) {
            querySubRegionList({parentId: data.id}).then(res => {
              const data = res.data.map(x => ({...x, leaf: true}))
              resolve(data)
            })
          } else if (level === 4) {
            querySubRegionList({parentId: data.id}).then(res => {
              const data = res.data.map(x => ({...x, leaf: true}))
              resolve(data)
            })
          } else {
            resolve([])
          }
        }
      },
      search: {
        regionList: []
      },
      tableList: [],
      isShowDialog: false,
      form: {
        page: 1,
        pageSize: 10,
      },
      currentRow: {
        address: '',
        email: '',
        gender: 0,
        loginName: '',
        password: '',
        repeat: '',
        phone: '',
        platformName: '',
        unitType: 0,
        unitTypeName: '',
        regionList: [],
        userName: '',
      },
      EnumUnitTypeList: [],
      rules: {
        loginName: {required: true, validator: CHECK_USERNAME},
        userName: {required: true, message: '请输入负责人姓名'},
        address: {required: true, message: '请输入详细地址'},
        platformName: {required: true, message: '请输入单位名称'},
        unitType: {required: true, message: '请选择平台类型', trigger: 'change'},
        phone: {required: true, validator: '请输入联系电话'},
        email: {validator: CHECK_EMAIL},
        password: {required: true, validator: CHECK_PASSWORD},
        phone: {required: true, validator: CHECK_PHONE},
        repeat: {validator: CHECK_REPEAT.bind(this)},
      },
    }
  },
  mixins:[Enums],
  computed: {
    // 弹窗的title
    dialogTitle() {
      return this.currentRow.id ? '编辑平台' : '新增平台'
    },
    // true  为编辑   false  accountQueryRoleList
    isEditStatus() {
      return !!this.currentRow.id
    },
    // 超级管理员才展示平台新增按钮
    isSuper() {
      return this.$store.state.userInfo.type === 1
    },
  },
  methods: {

    /**
     * row  当前操作行的对象
     */
    handleEdit(row) {
      this.currentRow = {...row, password: '', repeat: ''}
      this.isShowDialog = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    /**
     * 点击停用、启用切换文本
     * status 0正常，1锁定
     */
    _getSwitchInfo(status) {
      return status ? '停用后，账号无法登录本平台，确认停用？' : '启用该账号？'
    },
    // 获取当前的序号
    getIndex(index) {
      let param = (this.form.page - 1) * this.form.pageSize + index + 1
      return param
    },
    // 新增数据
    handleAdd() {
      this.currentRow = {
        name: '',
        description: null
      }
      this.isShowDialog = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    async queryList() {
      // 省市区搜索
      if (this.search.regionList) {
        this.form.regionList = this.search.regionList.join(',')
      }
      // 由于在前端进行过滤，所以name不能传到后端
      let res = await reviewQueryList(this.form)
      this.tableList = res.data?.records || []
      this.form.page = Number(res.data?.current)
      this.form.total = Number(res.data?.total)
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.form.pageSize = val
      this.queryList()
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.form.page = val
      this.queryList()
    },
    // 表单提交
    validateForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.currentRow = filterEmpty(this.currentRow)
          this.submitData()
        }
      })
    },
    encryptByDES(message, key) {
      var keyHex = cryptoJs.enc.Utf8.parse(key);
      var encrypted = cryptoJs.DES.encrypt(message, keyHex, {
        mode: cryptoJs.mode.ECB,
        padding: cryptoJs.pad.Pkcs7
      })
      return encrypted.ciphertext.toString();
    },
    // 新增编辑提交数据
    async submitData() {
      // 根据ID判断使用新增还是编辑

      let action = this.currentRow.id ? platformUpdate : platformAdd
      const {password, repeat, voucherList} = this.currentRow
      const DATA = {
        ...this.currentRow,
        voucherList: voucherList?.map(x => x.response.data.path),
        password: password ? this.encryptByDES(password,'interface.jgkj').toUpperCase(): null,
        repeat: repeat ? this.encryptByDES(repeat,'interface.jgkj').toUpperCase() : null
      }

      if (![1, 2, 3].includes(this.currentRow.unitType)) {
        this.currentRow.industryType = 1
        this.currentRow.regionType = 1
      }
      let res = await action(DATA)
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: this.currentRow.id ? '修改成功' : '添加成功'
        })
        this.isShowDialog = false
        this.queryList()
      }
      return res
    },
  },
  mounted() {
    // 查询单位类型
    this.queryDictList(['EnumUnitType'],['EnumUnitTypeList']).then(res => {
      if (this.$store.state.userInfo.type !== 1) {
        let list = []
        // 隐藏设备厂家选项
        res.map(x => {
          if (x.code != 3) {
            list.push(x)
          }
        })
        this.EnumUnitTypeList = list
      }
    })

  },
  activated() {
    this.queryList()
  },
  filters: {
    // 时间格式化
    formatTimer(timer) {
      return Format(new Date(timer), 'yyyy-MM-dd hh:mm:ss')
    },
    // 0正常，1锁定
    getStatusBtnMap(type) {
      return type ? '停用' : '启用'
    }
  },
  components: {RegionUnit2},
}
</script>

<style>

</style>
